<?php
  function get_vat_tu_autocomplete($string) {
    $query = db_select('dt_vat_tu', 'vt')->extend('PagerDefault');
    $query->fields('vt', array('ma_vat_tu', 'ten_vat_tu'));
    $query->condition(
      db_or()->
      condition('vt.ten_vat_tu', '%' . db_like($string) . '%', 'LIKE')->
      condition('vt.ma_vat_tu', $string, '=')->
      condition('vt.ma_vat_tu', 'VT_' . $string, '=')
    );
    $result = $query->limit(20)->execute();
    $data = array();
    while ($rs = $result->fetchObject()) {
      $data[$rs->ten_vat_tu . ' ['.$rs->ma_vat_tu.']'] = $rs->ten_vat_tu . ' ['.$rs->ma_vat_tu.']';
    }
    return $data;
  }

  function get_vat_tu_theo_ma($ma_vat_tu) {
    $query = db_select('dt_vat_tu', 'vt');
    $query->fields('vt', array('id', 'ma_vat_tu', 'ten_vat_tu'));
    $query->condition('vt.ma_vat_tu', $ma_vat_tu, '=');
    return $query->execute()->fetchObject();
  }

  function insert_loai_vat_tu($uid, $ten_vat_tu, $don_vi, $ghi_chu) {
    $trang_thai = 1;
    $so_luong = 0;
    $thoi_gian = time();
    $query = db_insert('dt_vat_tu');
    $arr = array(
      'uid' => $uid,
      'trang_thai' => $trang_thai,
      'ma_vat_tu' => '',
      'ten_vat_tu' => $ten_vat_tu,
      'don_vi' => $don_vi,
      'so_luong' => $so_luong,
      'ghi_chu' => $ghi_chu,
      'thoi_gian' => $thoi_gian
    );
    $query->fields(array_keys($arr));
    $query->values($arr);
    $id = $query->execute();
    $ma_vat_tu = $id;
    while (strlen($ma_vat_tu) < 3) {
      $ma_vat_tu = '0' . $ma_vat_tu;
    }
    $ma_vat_tu = 'VT_' . $ma_vat_tu;
    db_update('dt_vat_tu')
      ->fields(array(
        'ma_vat_tu' => $ma_vat_tu,
      ))
      ->condition('id', $id)
      ->execute();
    return $id;
  }

  function insert_vat_tu_phieu($uid, $thao_tac, $thoi_gian) {
    $query = db_insert('dt_vat_tu_phieu');
    $arr = array(
      'uid' => $uid,
      'thao_tac' => $thao_tac,
      'thoi_gian' => $thoi_gian
    );
    $query->fields(array_keys($arr));
    $query->values($arr);
    $id = $query->execute();
    return $id;
  }

  function insert_vat_tu_phieu_chi_tiet($uid, $pid, $id_vat_tu_arr, $so_luong_arr, $ghi_chu_arr, $thoi_gian) {
    $query = db_insert('dt_vat_tu_phieu_chi_tiet');
    $query->fields(array('uid', 'vid', 'pid', 'vid', 'so_luong', 'ghi_chu', 'thoi_gian'));
    $query->values($arr);
    $query->execute();
  }